package com.tsmti.lab.controller.activiti;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.tsmti.activiti.dto.ActUserDto;
import com.tsmti.activiti.entity.*;
import com.tsmti.activiti.service.*;
import com.tsmti.activiti.utils.ActConstants;
import com.tsmti.core.common.constant.Constants;
import com.tsmti.core.common.controller.BaseController;
import com.tsmti.core.common.model.AjaxJson;
import com.tsmti.core.common.query.data.Condition;
import com.tsmti.core.common.query.data.PageJson;
import com.tsmti.core.common.query.data.PropertyPreFilterable;
import com.tsmti.core.common.query.data.Queryable;
import com.tsmti.core.exception.MyException;
import com.tsmti.core.util.ConvertUtil;
import com.tsmti.core.util.JsonUtils;
import com.tsmti.core.util.ObjectUtils;
import com.tsmti.core.util.StringUtils;
import com.tsmti.system.service.OrganizationService;
import com.tsmti.system.service.RoleService;
import com.tsmti.system.service.UserService;
import com.tsmti.util.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Package：com.tsmti.lab.controller.activiti
 * @Class：ExtendActModelController
 * @Description： 流程模型相关操作
 * @Author：zcw
 * @Date：Created in 2018/8/16 20:28
 * @Company:
 * @Version：
 * @Modified By:
 *
 */
@Controller
@RequestMapping("act/model")
public class ExtendActModelController extends BaseController{
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(ExtendActModelController.class);

    @Autowired
    ExtendActModelerService extendActModelService;

    @Autowired
    ActModelerService actModelerService;

    @Autowired
    ExtendActNodeSetService nodesetService;

    @Autowired
    ExtendActNodeFieldService fieldService;

    @Autowired
    ExtendActNodeUserService nodeuserService;

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    OrganizationService organService;

    @Autowired
    ExtendActBusinessService businessService;

    /**
     * 列表
     * @param model
     * @param actModelEntity
     * @param request
     * @return
     */
    @RequestMapping("list")
    @RequiresPermissions("act:model:all")
    public String list(Model model, ExtendActModel actModelEntity,Queryable queryable, PropertyPreFilterable propertyPreFilterable,  HttpServletRequest request,HttpServletResponse response){
        DetachedCriteria detachedCriteria  = DetachedCriteria.forClass(ExtendActModel.class);
        SerializeFilter filter = propertyPreFilterable.constructFilter(ActUserDto.class);
        PageJson<ExtendActModel> pagejson = new PageJson<ExtendActModel>(extendActModelService.findPage(queryable.getPageable(),detachedCriteria));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
        model.addAttribute("model",actModelEntity);
        return "activiti/extendActModelList";
    }

    /**
     * 编辑弹框
     * @param model
     * @return
     */
    @RequestMapping("info")
    @RequiresPermissions("act:model:all")
    public String info(Model model, String id){
        ExtendActModel extendActModel = new ExtendActModel();
        if(StringUtils.isNotEmpty(id)){
            extendActModel = extendActModelService.get(id);
            if(extendActModel == null){
                extendActModel = new ExtendActModel();
            }
            List<ExtendActBusiness> businessEntityList = businessService.queryBusTree();
            model.addAttribute("busTree", JsonUtils.getJsonByObj(businessEntityList));
        }
        model.addAttribute("data", extendActModel);
        return "activiti/modelInfo";
    }

    /**
     * 保存
     * @param modelEntity
     * @return
     */
    @RequestMapping("save")
    @ResponseBody
    @RequiresPermissions("act:model:all")
    public AjaxJson save(ExtendActModel modelEntity){
        AjaxJson result = null;
        try {
           extendActModelService.createModel(modelEntity);
           result = AjaxJson.success();
        } catch (Exception e) {
            e.printStackTrace();
            result = AjaxJson.fail();
        }
        return result;
    }

    /**
     * 更新
     * @param modelEntity
     * @return
     */
    @RequestMapping("update")
    @ResponseBody
    @RequiresPermissions("act:model:all")
    public AjaxJson update(ExtendActModel modelEntity){
        AjaxJson result = null;
        try {
            extendActModelService.update(modelEntity);
            result = AjaxJson.success("更新"+modelEntity.getName()+"成功!");
        }catch (Exception e){
            logger.error(e.getMessage());
            result = AjaxJson.success("更新"+modelEntity.getName()+"失败!");
        }
        return result;
    }

    /**
     * 获取流程图所有节点和连线
     * @param modelId 模型id
     */
    @RequestMapping("flowTree")
    public String flowTree(String modelId,Model model) throws Exception {
        //所有节点
        List<Map<String, String>> flows = actModelerService.getflows(modelId);
        model.addAttribute("flows", JsonUtils.getJsonByObj(flows));
        //所有回调和业务相关设置
        ExtendActBusiness bus = new ExtendActBusiness();
        bus.setType(ActConstants.ActBusType.BACK.getValue());
        ExtendActBusiness businessEntity = businessService.queryActBusByModelId(modelId);
        List<ExtendActBusiness> callBacks = businessService.queryCalBackByPid(businessEntity.getId());
        model.addAttribute("calBacks", JsonUtils.getJsonByObj(callBacks));
        model.addAttribute("writes", businessEntity.getWrites());
        model.addAttribute("judgs", businessEntity.getJudgs());
        model.addAttribute("userFields", businessEntity.getUserFields());
        model.addAttribute("data",new ExtendActNodeSet());
        return "activiti/flowNodeSet";
    }

    /**
     * 获取节点的扩展设置信息
     * @return
     */
    @RequestMapping("flowSetInfo")
    @ResponseBody
    public AjaxJson flowSetInfo(String nodeId,String type){
        if(StringUtils.isEmpty(nodeId)){
            throw new MyException("未获取节点id");
        }
        AjaxJson result = AjaxJson.success();
        ExtendActNodeSet nodeSet = nodesetService.queryByNodeId(nodeId);
        if(nodeSet != null){
            ExtendActModel actModel = extendActModelService.findByModelId(ConvertUtil.null2String(nodeSet.getModelId()));
            nodeSet.setDefId(ConvertUtil.null2String(actModel.getDefId()));
        }

        //如果节点类型为审批节点
        if(ActConstants.NodeType.EXAMINE.getValue().equals(type)){
            //用户列表
            List<ExtendActNodeUser> userLists = nodeuserService.getNodeUserByNodeId(nodeId);
            result.put("userList",userLists);
            //表单字段配置
            String userField = "";
            ExtendActNodeUser nodeUserField =  nodeuserService.getNodeUserFieldByNodeId(nodeId);
            if(nodeUserField != null){
                userField = ConvertUtil.null2String(nodeUserField.getUserNo());
            }
            nodeSet.setUserField(userField);
        }
        //节点类型为连线
        if(ActConstants.NodeType.LINE.getValue().equals(type)){
            Map<String,Object> params = new HashMap<>(16);
            params.put("nodeId",nodeId);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ExtendActNodeField.class);
            detachedCriteria.add(Restrictions.eq("nodeId",nodeId));
            detachedCriteria.add(Restrictions.eq("delFlag",0));
            List<ExtendActNodeField> fields = fieldService.list(detachedCriteria);
            result.put("fields",fields);
        }
        result.put("nodeSet",nodeSet);
        return result;
    }

    /**
     * 选择审批范围弹框
     * @param request
     * @param queryable
     * @param propertyPreFilterable
     * @return
     */
    @RequestMapping(value = "userAreaSelect")
    public String userAreaSelect(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request, HttpServletResponse response, String type){
        return "activiti/userAreaSelect";
    }
    @RequestMapping(value = "getUserList")
    public void getUserList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request, HttpServletResponse response, String type){
        Map<String,Object> params = new HashMap<>(2);
        Condition condition = queryable.getCondition();
        params.put("orgId", UserUtils.getOrgId());
        if(queryable.getCondition() != null){
            for (Condition.Filter filter : condition) {
                String value = ConvertUtil.null2String(filter.getValue());
                if (!ObjectUtils.isNullOrEmpty(value)) {
                    params.put(filter.getProperty(),value);
                }
            }
        }

        if(!params.containsKey(Constants.USER_TYPE)){
            //默认审批类型为用户级别的
            params.put(Constants.USER_TYPE,ActConstants.ExamineType.USER.getValue());
        }
        SerializeFilter filter = propertyPreFilterable.constructFilter(ActUserDto.class);

        PageJson<ActUserDto> pagejson = new PageJson<ActUserDto>( actModelerService.findActUser(params,queryable));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    /**
     * 查看流程图片
     * @param modelId
     * @return
     */
    @RequestMapping(value = "showFlowImg")
    @RequiresPermissions("act:model:all")
    public ResponseEntity<byte[]> showFlowImg(String modelId){
        return actModelerService.showFlowImg(modelId);
    }


    /**
     * 删除模型
     * @param id
     * @return
     */
    @RequestMapping("del")
    @ResponseBody
    @RequiresPermissions("act:model:all")
    public AjaxJson del(String id){
        try {
            extendActModelService.removeById(id);
            return AjaxJson.success("删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除失败",e);
            return AjaxJson.fail();
        }
    }

    /**
     * 保存节点设置
     * @param nodesetEntity 流程节点配置
     * @return
     */
    @RequestMapping(value = "saveNode",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("act:model:all")
    public AjaxJson saveNode(ExtendActNodeSet nodesetEntity){
        try {
            ExtendActNodeSet nodeSet = nodesetService.saveNode(nodesetEntity);
            return AjaxJson.success("保存成功!").put("nodeSet",nodeSet);
        } catch (IOException e) {
            logger.error("保存节点失败",e);
            return AjaxJson.fail("保存失败!");
        }
    }

    /**
     * 部署流程
     * @param modelId 模型id
     * @return
     */
    @RequestMapping(value = "deploy",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("act:model:all")
    public AjaxJson deploy(String modelId){
        try {
            extendActModelService.deploy(modelId);
            return AjaxJson.success();
        } catch (IOException e) {
            logger.error("部署流程失败",e);
            return AjaxJson.fail();
        }
    }
}
